package com.erp.gather.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.erp.gather.domain.ErpCollectProductTask;
import com.erp.gather.domain.bo.ErpCollectProductTaskBo;
import com.erp.gather.domain.vo.ErpCollectProductTaskVo;
import com.erp.gather.mapper.ErpCollectProductMapper;
import com.erp.gather.mapper.ErpCollectProductTaskMapper;
import com.erp.gather.service.IErpCollectProductTaskService;
import com.ruoyi.common.core.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.web.oldController.BaseController;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.gather.api.domain.ErpCollectProduct;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.util.Strings;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 采集商品任务
 *
 * @author erp
 * @date 2023-03-13
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/gather/collectProductTask")
public class ErpCollectProductTaskController extends BaseController {

    private final IErpCollectProductTaskService iErpCollectProductTaskService;
    private final ErpCollectProductTaskMapper erpCollectProductTaskMapper;
    private final ErpCollectProductMapper erpCollectProductMapper;

    @Resource
    RemoteUserService remoteUserService;

    @GetMapping("/userDict")
    public List<Map<String, Object>> UserDict() {
        //TODO 用户信息 内部类调用 有bug上面方法能調用，下面方法無法調用
        R<Object> objectTwo = remoteUserService.queryRoleByKey("erp-operate");
        R<Object> objectOne = remoteUserService.queryRoleByKey("gather-staff");
        ArrayList<SysUser> sysUserList = new ArrayList<>();
        List<SysUser> sysUserOneList = JSONArray.parseArray(JSONObject.toJSONString(objectOne.getData()),SysUser.class);
//        ArrayList<SysUser> sysUserOneList = (ArrayList<SysUser>) objectOne.getData();
        if (ObjectUtils.isNotNull(sysUserOneList)) {
            sysUserList.addAll(sysUserOneList);
        }
        List<SysUser> sysUserTwoList = JSONArray.parseArray(JSONObject.toJSONString(objectTwo.getData()),SysUser.class);
//        ArrayList<SysUser> sysUserTwoList = (ArrayList<SysUser>) objectTwo.getData();
        if (ObjectUtils.isNotNull(sysUserTwoList)) {
            sysUserList.addAll(sysUserTwoList);
        }
        List<HashMap<String, Object>> collect = new ArrayList<>();

        for (SysUser user : sysUserList) {
            HashMap<String, Object> map= new HashMap<>();
            map.put("dictLabel", user.getNickName());
            map.put("dictValue", user.getUserId());
            collect.add(map);
        }
//        List<HashMap<String, Object>> collect =
//                sysUserList.stream().map(item -> new HashMap<String, Object>() {
//                    {
//                        put("dictLabel", item.getNickName());
//                        put("dictValue", item.getUserId());
//                    }
//                }).collect(Collectors.toList());

        HashMap<Long, HashMap<String, Object>> res = new LinkedHashMap<>();
        collect.forEach(hash -> {
            res.put(Long.valueOf(hash.get("dictValue") + ""), hash);
        });

        return new ArrayList<Map<String, Object>>(res.values());

    }

    @Transactional(rollbackFor = Exception.class)
    @GetMapping("updateCollectId")
    public R<Void> updateCollectId(ErpCollectProductTaskBo bo) {
        if (bo.getCollectUserId() == null) {
            return R.fail("采集人员不能为空");
        }
        if (Strings.isBlank(bo.getIds())) {
            return R.fail("采集链接不能为空");
        }
        List<String> ids = Arrays.asList(bo.getIds().split(","));
        if (ids.size() == 0) {
            return R.fail("采集链接不能为空");
        }
        List<ErpCollectProductTask> erpCollectProductTasks = new ArrayList<>();
        List<ErpCollectProduct> erpCollectProducts = new ArrayList<>();
        for (String id : ids) {
            erpCollectProductTasks.add(new ErpCollectProductTask() {
                {
                    setId(Long.valueOf(id));
                    setCollectUserId(bo.getCollectUserId());
                }
            });
            ErpCollectProductTask erpCollectProductTask = erpCollectProductTaskMapper.selectById(Long.valueOf(id));
            List<Long> productIds = erpCollectProductMapper
                    .selectList(Wrappers.lambdaQuery(new ErpCollectProduct()).like(ErpCollectProduct::getCollectUrl,
                            erpCollectProductTask.getCollectUrl()))
                    .stream().map(ErpCollectProduct::getId).collect(Collectors.toList());
            productIds.forEach(productId -> {
                erpCollectProducts.add(new ErpCollectProduct() {
                    {
                        setId(productId);
                        setCollectUserId(bo.getCollectUserId());
                    }
                });
            });
        }
        if (erpCollectProductTasks != null && erpCollectProductTasks.size() != 0)
            erpCollectProductTaskMapper.updateBatchById(erpCollectProductTasks);
        if (erpCollectProducts != null && erpCollectProducts.size() != 0)
            erpCollectProductMapper.updateBatchById(erpCollectProducts);
        return R.ok();
    }

    /**
     * 查询采集商品任务列表
     */
    @GetMapping("/list")
    public TableDataInfo<ErpCollectProductTaskVo> list(ErpCollectProductTaskBo bo, PageQuery pageQuery) {
        TableDataInfo<ErpCollectProductTaskVo> result = iErpCollectProductTaskService.queryPageList(bo, pageQuery);
        result.getRows().forEach(row -> {
            //TODO 用户信息 内部类调用 已改造完成 待測試
            try {
                R<Object> objectOne = remoteUserService.selectUserById(row.getCollectUserId());
                System.out.println(objectOne.getMsg()+objectOne.getData());
                JSONObject sysUserOne = new JSONObject();
                if (objectOne.getCode() == 200) {
                    sysUserOne = JSONObject.parseObject(objectOne.getData().toString());
                }
                row.setCollectUserName(sysUserOne == null ? "" : sysUserOne.getString("nickName"));
                R<Object> objectTwo = remoteUserService.selectUserById(Long.valueOf(row.getCreateBy()));
                System.out.println(objectTwo);
                JSONObject sysUserTwo = new JSONObject();
                if (objectTwo.getCode() == 200) {
                    sysUserTwo = JSONObject.parseObject(objectTwo.getData().toString());
                }
                row.setCreateBy(sysUserTwo == null ? "" : sysUserOne.getString("nickName"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return result;
    }

    /**
     * 获取采集商品任务详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<ErpCollectProductTaskVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        return R.ok(iErpCollectProductTaskService.queryById(id));
    }

    /**
     * 新增采集商品任务
     */
    @RepeatSubmit()
    @PostMapping()
    public R<Object> add(@Validated(AddGroup.class) @RequestBody ErpCollectProductTaskBo bo) {
        Map<String, Object> map = iErpCollectProductTaskService.insertByBo(bo);
        return R.ok(map);
    }

    /**
     * 修改采集商品任务
     */
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ErpCollectProductTaskBo bo) {
        return toAjax(iErpCollectProductTaskService.updateByBo(bo));
    }

    /**
     * 删除采集商品任务
     *
     * @param ids 主键串
     */
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        return toAjax(iErpCollectProductTaskService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
